<!-- 添加受试者 -->
<template>
  <div>
    <a-modal
      width="800"
      title="邀请受试者"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :footer="null"
      @cancel="handleCancel"
    >
      <!-- 弹框主体 start -->
      <a-table bordered :loading="tableLoading" :columns="columns" :dataSource="data" :pagination="false">
        <!-- table template start -->
        <!-- table操作栏 -->
        <template slot="title">
          <span style="display: flex;">
            <a-button style="margin-right: 8px" icon="plus" @click="activeSecondModal">添加</a-button>
            <a-button v-if="visible && $auth('PROJECT.PROJECT_PATIENT_INVITE')" :href="$const.TEMPLATE_PATH.SUBJECT| dealImageUrl" icon="download" style="margin-right: 8px">模板下载</a-button>
            <a-upload
              v-if="visible && $auth('PROJECT.PROJECT_PATIENT_INVITE')"
              style="width: 30%;"
              accept=".xlsx"
              name="file"
              :before-upload="beforeUpload"
              list-type="picture"
              :preview-file="previewFile"
            >
              <a-button v-if="fileList.length < 1"> <a-icon type="upload" @change="handleChange()" /> 导入表格 </a-button>
            </a-upload>
          </span>
        </template>
        <template slot="siteOrgName" slot-scope="text, record">
          <span>{{ record.siteOrgName }}</span>
        </template>
        <!-- table template end -->
        <!-- 动态输入开始 -->
        <template v-for="col in ['ptsNo', 'ptsName' , 'ptsIdentity']" :slot="col" slot-scope="text, record">
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleInputChange(e.target.value, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="ptsPhone" slot-scope="text, record">
          <a-input
            v-if="record.editable"
            key="ptsPhone"
            style="margin: -5px 0"
            :value="text"
            :maxLength="11"
            @change="e => handleInputChange(e.target.value, record.key, 'ptsPhone')"
          />
          <template v-else>{{ text }}</template>
        </template>
        <!-- 选择操作 -->
        <template slot="ptsStatus" slot-scope="text, record">
          <a-select
            style="margin: -5px 0; width: 100%"
            :value="text"
            v-if="record.editable"
            @change="e => handleSelectChange(e, record.key, 'ptsStatus')"
          >
            <!-- <a-select-option :value="1"> 待筛选 </a-select-option>
            <a-select-option :value="2"> 待筛中 </a-select-option> -->
            <a-select-option v-for="item in $const.PTS_STATUS" :key="item.value" :value="item.value"> {{ item.desc }} </a-select-option>
          </a-select>
          <template v-else>{{ text | enumValueByKey($const.PTS_STATUS) }}</template>
        </template>
        <!-- 操作模块 -->
        <template slot="operation" slot-scope="text, record">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">添加</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record)">保存</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.key)">取消</a>
            </span>
          </template>
          <span v-else>
            <a @click="toggle(record.key)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <!-- 弹框主体 end -->
      <div class="footer-view">
        <a-space size="middle">
          <a-button @click="handleCancel">取消</a-button>
          <a-button :loading="confirmLoading" type="primary" @click="handleOk(1)" ghost>保存</a-button>
          <a-button :loading="confirmLoading" type="primary" @click="handleOk(2)" >邀请</a-button>
        </a-space>
      </div>
    </a-modal>

    <!-- 二级弹框 start -->
    <a-modal title="添加受试者" :visible="secondVisible" @ok="handleSecondOk()" @cancel="handleSecondCancel" centered>
      <!-- 二级弹框表单 -->
      <!-- <div>{{ centerList }}</div> -->
      <a-form-model ref="ruleForm" :model="form" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="选择site" prop="researchId">
          <a-select v-model="form.researchId">
            <a-select-option v-for="item in centerList" :value="item.id" :key="item.id">
              {{ item.orgName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="受试者数量" prop="count">
          <!-- <a-slider v-model="form.count" id="test" :max="100" /> -->
          <a-input-number :max="100" :min="1" style="width: 100%" v-model="form.count" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import monitor from '@/utils/monitor'
import addSubjectModal from '@/monitor/views/overview/detail/responsible/components/subject/addSubjectModal.js'

import { getContractCenter } from '@/api/overview/member'
import { getSubjectExport, getaAddPtsTable } from '@/api/overview/subject'
import { exportExcel } from '@/utils/util'

const watch = monitor(addSubjectModal)

export default {
  name: 'AddVisitModel',
  props: {
    datailId: {
      type: [String, Number],
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    }
    // centerList: {
    //   type: Array,
    //   default: () => {
    //     return []
    //   }
    // }
  },
  filters: {
    findNameById (val) {
      return val === 1 ? '待筛选' : '筛选中'
    }
  },
  data () {
    return {
      headers: {
        authorization: 'authorization-text'
      },
      fileList: [],
      data: [], // table data
      centerList: [],
      secondVisible: false,
      confirmLoading: false,
      tableLoading: false,
      form: {
        researchId: null,
        count: 1
      },
      formRules: {
        researchId: [{ required: true, message: '请选择', trigger: 'change' }],
        count: [{ required: true, message: '请输入数量', trigger: 'change' }]
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      columns: [
        {
          title: '序列',
          dataIndex: 'key',
          key: 'key'
        },
        {
          title: '研究中心',
          dataIndex: 'siteOrgName',
          key: 'siteOrgName',
          scopedSlots: { customRender: 'siteOrgName' }
        },
        {
          title: '受试者姓名',
          dataIndex: 'ptsName',
          key: 'ptsName',
          scopedSlots: { customRender: 'ptsName' }
        },
        {
          title: '受试者编号',
          dataIndex: 'ptsNo',
          key: 'ptsNo',
          scopedSlots: { customRender: 'ptsNo' }
        },
        {
          title: '受试者状态',
          dataIndex: 'ptsStatus',
          key: 'ptsStatus',
          width: '15%',
          scopedSlots: { customRender: 'ptsStatus' }
        },
        {
          title: '身份证号',
          dataIndex: 'ptsIdentity',
          key: 'ptsIdentity',
          scopedSlots: { customRender: 'ptsIdentity' }
        },
        {
          title: '电话/手机',
          dataIndex: 'ptsPhone',
          key: 'ptsPhone',
          scopedSlots: { customRender: 'ptsPhone' }
        },
        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      queryParam: {
        proId: this.datailId
      }
    }
  },
  mounted () {
    this.getCenterList()
  },
  methods: watch({
    // 过滤出所选机构的名字将其一起带给form表单
    filterOrgName () {
      const target = this.centerList.find(item => item.id === this.form.researchId)
      return target.orgName
    },
    // 上传文件
    beforeUpload (file) {
      // 定义可选文件类型
      const fileType = file.name.split('.')[1]
      console.log(fileType)
      return false
    },
    previewFile (file) {
      const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isJpgOrPng) {
        this.$notification.error({
          message: file.name,
          description: '仅支持文件格式: .xlsx 格式文件!'
        })
        return false
      } else {
        const params = new FormData()
        params.append('file', file)
        params.append('proId', this.$route.query.id)
        return getaAddPtsTable(params).then(res => {
          this.$emit('import')
          this.$notification.success({
            message: file.name,
            description: '上传成功'
          })
          console.log(res)
        })
      }
    },
    // 上传文件end
    handleChange (info) {
      console.log(info)
      this.fileList = info.fileList
      this.cUrl = info.fileList[0].response.data
    },
    getCenterList () {
      // centerList({ proId: this.$route.query.id, deleted: 0 }).then(res => {
      getContractCenter({ proId: this.$route.query.id, deleted: 0 }).then(res => {
        this.centerList = res.content
      })
    },
    // 导入表格
    importForm () {
      getSubjectExport(this.queryParam).then(res => {
        this.$message.success('导出成功')
        exportExcel('日志', res)
      })
    },
    // 开始添加 批量插入row开始
    activeSecondModal () {
      this.secondVisible = true
    },
    /* *****************行编辑处理****************** */
    // 删除行
    remove (key) {
      const newData = this.data.filter(item => item.key !== key)
      this.data = newData
    },
    // 行状态切换
    toggle (key) {
      const target = this.data.find(item => item.key === key)
      target._originalData = { ...target }
      target.editable = !target.editable
      console.log(this.data)
      this.$forceUpdate()
    },
    // input输入事件
    handleInputChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        if (column === 'ptsNo') {
          value = this.$options.filters.checkUnChinese(value)
        }
        target[column] = value
        this.data = newData
      }
    },
    // 校验输入的手机号
    checkPhone (val) {
      const pattern = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      return pattern.test(val)
    },
    // select选择事件
    handleSelectChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        target[column] = value
        this.data = newData
      }
      this.$forceUpdate()
    },
    // 取消事件，还原原本行数据
    cancel (key) {
      const target = this.data.find(item => item.key === key)
      Object.keys(target).forEach(key => {
        target[key] = target._originalData[key]
      })
      target._originalData = undefined
    },
    // row保存
    saveRow (record) {
      this.tableLoading = true
      const { key, ptsNo, ptsStatus, ptsPhone, ptsIdentity } = record // 需要校验的必填字段
      if (!ptsNo || !ptsStatus || !ptsPhone || !ptsIdentity) {
        this.tableLoading = false
        this.$message.error('请填写完整信息')
        return
      }
      if (!this.checkPhone(ptsPhone)) {
        this.tableLoading = false
        this.$message.error('手机号码格式错误')
        return
      }
      if (!/^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/.test(ptsIdentity)) {
        this.tableLoading = false
        this.$message.error('身份证格式错误')
        return
      }
      // 模拟网络请求、卡顿 100ms, 不需要走接口，去掉即可
      new Promise(resolve => {
        setTimeout(() => {
          resolve({ loop: false })
        }, 100)
      }).then(() => {
        const target = this.data.find(item => item.key === key)
        delete target._originalData // 删除克隆字段，防止编辑出现该部分
        // 上面一行最后的“key”是否应为“record.key”?
        target.editable = false
        target.isNew = false
        this.tableLoading = false
      })
    },
    /* *****************弹框回调处理****************** */
    handleOk (type) {
      console.log('组件中data', this.data)
      if (!this.data.length) {
        this.$message.error('受试者不可为空')
        return false
      }
      const flag = this.data.find(item => item.isNew === true)
      if (flag) {
        this.$message.error('请先将每行进行保存再提交')
        return false
      }
      this.addInvite()
      this.$emit('ok', this.data, type)
    },
    handleCancel () {
      this.$emit('cancel')
    },
    // 根据填写数据遍历列表
    handleSecondOk () {
      // 校验
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const len = this.data.length
          const count = this.form.count + len
          const siteOrgName = this.filterOrgName()
          for (let i = len; i < count; i++) {
            this.data.push({
              key: i + 1,
              ptsNo: '',
              researchId: this.form.researchId,
              // siteOrgName: this.form.researchId.orgName,
              siteOrgName,
              ptsStatus: '',
              ptsPhone: '',
              ptsIdentity: '',
              editable: true,
              isNew: true
            })
          }
          this.handleSecondCancel()
        }
      })
    },
    // 关闭并重置弹窗
    handleSecondCancel () {
      this.secondVisible = false
      setTimeout(() => {
        this.$refs.ruleForm.resetFields()
        this.form = this.$options.data().form
      }, 200)
    },
    // 邀请受试者埋点
    addInvite () {}
  })
}
</script>
<style scoped lang="less">
  .footer-view{
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
</style>
